import Mn from 'backbone.marionette';
import TextAreaWidget from '../../../../../widgets/TextAreaWidget.js';
import InputWidget from '../../../../../widgets/InputWidget.js';
import BaseFormBehavior from "../../../../../base/behaviors/BaseFormBehavior.js";
import {
    serializeForm
} from "../../../../../tools";


const DiscountPercentView = Mn.View.extend({
    tagName: 'div',
    className: 'modal_overflow',
    behaviors: [BaseFormBehavior],
    template: require('./templates/DiscountPercentView.mustache'),
    regions: {
        'description': '.description',
        'percentage': '.percentage'
    },
    ui: {
        form: 'form',
        submit: "button[type=submit]",
        btn_cancel: "button[type=reset]",
    },
    triggers: {
        'click @ui.btn_cancel': 'cancel:form',
    },
    childViewTriggers: {
        'change': 'data:modified',
    },
    events: {
        'submit @ui.form': "onSubmit"
    },
    serializeForm() {
        return serializeForm(this.getUI('form'));
    },
    syncFormWithModel() {
        /* Set form datas on the model and fires datas validation */
        var datas = this.serializeForm();
        this.model.set(datas, {
            validate: true
        });
        return datas;
    },
    onSubmit: function (event) {
        event.preventDefault();
        let datas = this.syncFormWithModel();
        if (this.model.isValid(_.keys(datas))) {
            this.triggerMethod('insert:percent', this.model);
        }
    },
    onRender: function () {
        this.showChildView(
            'description',
            new TextAreaWidget({
                title: "Description",
                field_name: "description",
                tinymce: true,
                cid: '11111'
            })
        );
        this.showChildView(
            'percentage',
            new InputWidget({
                title: "Pourcentage",
                field_name: 'percentage',
                addon: "%"
            })
        );
        this.trigger('data:modified', 'description', '');
    },
    templateContext: function () {
        return {
            title: this.getOption('title'),
        };
    }

});
export default DiscountPercentView;